package com.sczmgk.hotline.mainhomeview.mainhomehome;

import android.app.Activity;
import android.os.Handler;
import android.os.Message;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.RelativeLayout;

import com.google.gson.Gson;
import com.sczmgk.frame.http.Tools;
import com.sczmgk.hotline.R;
import com.sczmgk.hotline.adapter.ArticleAdapter;
import com.sczmgk.hotline.adapter.PointAdapter;
import com.sczmgk.hotline.base.MainHomeBaseView;
import com.sczmgk.hotline.callback.ParseJsonCallback;
import com.sczmgk.hotline.constant.Constant;
import com.sczmgk.hotline.entity.ArticleInfo;
import com.sczmgk.hotline.entity.ArticleListData;
import com.sczmgk.hotline.entity.BannerInfo;
import com.sczmgk.hotline.httpUtils.MyHttp;
import com.sczmgk.hotline.utils.CacheUtils;
import com.sczmgk.hotline.utils.CommonUtils;
import com.sczmgk.hotline.utils.MyLog;
import com.sczmgk.hotline.utils.MyToast;
import com.sczmgk.hotline.view.MyListView;
import com.sczmgk.hotline.view.refreshview.PullRefreshUtil;
import com.sczmgk.hotline.view.refreshview.PullRefreshView;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * Created by Administrator on 2016/2/26.
 * 我的
 */
public class MainHomeHomePage extends MainHomeBaseView {

    /**
     * 刷新主页数据
     */
    private static final int REFRESH_HOME_UI = 1;

    /**
     * 加载更多隐藏
     */
    private static final int HIDE_FOOTER_HEADER = 2;

    /*加载更多类型*/
    private static final String LOAD_MORE = "load_more";

    /*下拉刷新类型*/
    private static final String LOAD_NORMAL = "load_normal" ;

    /*banner*/
    private ViewPager mVpBanner;

    /*轮播的小点容器*/
    private LinearLayout mLayoutPointGroup;

    /*选中的小点*/
    private View mSelectedPoint;

    /*整个banner的容器*/
    private RelativeLayout mBannerContainer;

    /*小点容器*/
    private RelativeLayout mPointContainer;

    /*列表*/
    private MyListView mListView;

    /*顶部banner的集合*/
    private List<BannerInfo> bannerInfos;

    /*图片的集合*/
    private List<ImageView> imageViewList;

    /*轮播handler*/
    private MyHandler myHandler;

    /*文章列表的集合*/
    private List<ArticleInfo> articleInfos;

    /*文章列表的adapter*/
    private ArticleAdapter articleAdapter;

    private int pointSize;

    private int basicWidth = -1;

    private PointAdapter pointAdapter;

    /*下拉刷新的控件*/
    private PullRefreshView mRefreshView;

    private int nowpage;
    private int totalpage;

    /*是否第一次进入*/
    private boolean isFirstIn = true ;

    /*缓存数据*/
    private String cacheData;

    private int articleid ;

    public MainHomeHomePage(Activity context, int articleid) {
        super(context);
        this.articleid = articleid;
        initTitle();
        initView();
        initData();
        setListener();
    }

    /**
     * 初始化标题
     */
    private void initTitle() {
        setHeadViewVisibility(View.GONE);
    }

    @Override
    public void mHandleMessage(Message msg) {
        if (mRefreshView != null){
            mRefreshView.refreshFinish();
        }
        switch (msg.what) {
            case REFRESH_HOME_UI:
                //刷新主页数据

                //处理轮播
                if (bannerInfos != null && bannerInfos.size() > 0) {
                    //设置adapter
//                    pointAdapter.setList(bannerInfos);
//                    pointAdapter.notifyDataSetChanged();

                    //设置banner的adapter
                    pointAdapter = new PointAdapter(activity, bannerInfos);
                    mVpBanner.setAdapter(pointAdapter);
                    initPointView();
                    mBannerContainer.setVisibility(View.VISIBLE);
                    if (bannerInfos.size() == 1){
                        mPointContainer.setVisibility(View.GONE);
                    }else{
                        mPointContainer.setVisibility(View.VISIBLE);
                        processPlay();
                    }
                } else {
                    mBannerContainer.setVisibility(View.GONE);
                }

                articleAdapter.setList(articleInfos);
                articleAdapter.notifyDataSetChanged();

                break;
        }
    }

    /**
     * 初始化View
     */
    @Override
    public void initView() {

        //填充布局
        LayoutInflater inflater = LayoutInflater.from(activity);
        View pageView = inflater.inflate(R.layout.main_home_page, null);

        mVpBanner = (ViewPager) pageView.findViewById(R.id.vp_main_home_home_banner);
        mLayoutPointGroup = (LinearLayout) pageView.findViewById(R.id.ll_main_home_home_point_group);
        mSelectedPoint = pageView.findViewById(R.id.v_main_home_home_selected_point);
        mPointContainer = (RelativeLayout) pageView.findViewById(R.id.rl_main_home_home_banner_point_container);
        mBannerContainer = (RelativeLayout) pageView.findViewById(R.id.rl_main_home_home_banner_container);
        mListView = (MyListView) pageView.findViewById(R.id.lv_main_home_home);
        mListView.setFocusable(false);
        mRefreshView = (PullRefreshView) pageView.findViewById(R.id.refresh_view);

        container.addView(pageView);//返回当前的View
    }

    private void initData() {

        //banner的list
        bannerInfos = new ArrayList<>();

        //文章列表的集合
        articleInfos = new ArrayList<>();

        //设置list的adapter
        articleAdapter = new ArticleAdapter(activity, articleInfos);
        mListView.setAdapter(articleAdapter);

        //取缓存
        String cacheKey = getCacheKey() + "_" + articleid;
        cacheData = CacheUtils.getStringData(activity, cacheKey, "");
        MyLog.d(TAG,"cacheData : " + cacheData);
        if (!Tools.isEmpty(cacheData)) {
            try {
                parseData(cacheData,LOAD_NORMAL);
            } catch (Exception e) {
                MyLog.e(TAG, "解析json错误");
                e.printStackTrace();
            }
        }
    }

    private void setListener() {

        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                MyToast.show(activity,"mListView item : " + i);
            }
        });

        PullRefreshUtil.setRefresh(mRefreshView, true,true);
        mRefreshView.setOnPullDownRefreshListener(new PullRefreshView.OnPullDownRefreshListener() {
            @Override
            public void onRefresh() {
//                mRefreshView.isMore(true);
                loadData(articleid,1,LOAD_NORMAL);
            }
        });

        mRefreshView.setOnPullUpRefreshListener(new PullRefreshView.OnPullUpRefreshListener() {
            @Override
            public void onRefresh() {
                if (nowpage < totalpage){
                    loadData(articleid,nowpage + 1,LOAD_MORE);
                }else{
                    Message msg = Message.obtain();
                    msg.what = HIDE_FOOTER_HEADER;
                    mHandler.sendMessage(msg);
                    MyToast.show(activity, "没有更多数据！");
                }
            }
        });
    }

    private void initPointView() {

        if (bannerInfos == null) {
            mBannerContainer.setVisibility(View.GONE);
            return;
        }

        mBannerContainer.setVisibility(View.VISIBLE);
        mPointContainer.setVisibility(View.VISIBLE);

        mLayoutPointGroup.removeAllViews();
        //引导图片
        imageViewList = new ArrayList<>();

        ImageView iv;
        View view;
        //取得像素密度
        float screenDensity = CommonUtils.getScreenDensity(activity);
        pointSize = (int) (5 * screenDensity);
        //初始化
        for (int i = 0; i < bannerInfos.size(); i++) {
            iv = new ImageView(activity);
            //加入引导图片
            imageViewList.add(iv);
            //实例化小点
            view = new View(activity);

            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(pointSize, pointSize);
            if (i != 0) {
                //设置第一个点后面的 maginLeft
                params.leftMargin = pointSize;
            }
            //设置小点参数
            view.setLayoutParams(params);
            //设置小点背景
            view.setBackgroundResource(R.drawable.banner_point_no_selected_bg);
            //加入小点
            mLayoutPointGroup.addView(view);
        }

        mVpBanner.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
            @Override
            public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {

                //移动小点
                int childCount = mLayoutPointGroup.getChildCount();
                if ((basicWidth == -1 || basicWidth ==0) && childCount > 1) {
                    //取得第二个小点的与第一个小点的距离
                    basicWidth = mLayoutPointGroup.getChildAt(1).getLeft() - mLayoutPointGroup.getChildAt(0).getLeft();
                }
                int leftMargin = (int) ((position + positionOffset) * basicWidth);

                RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) mSelectedPoint.getLayoutParams();
                layoutParams.leftMargin = leftMargin;
                mSelectedPoint.setLayoutParams(layoutParams);
            }
        });
    }

    /**
     * 处理无限轮播
     */
    private void processPlay() {

        // 发送延迟消息，切换轮播图
        if (myHandler == null) {
            myHandler = new MyHandler();
        }
        // 把前面发送的消息删除
        myHandler.removeCallbacksAndMessages(null);// null 删除所有的Callbacks 和Messages
        myHandler.sendMessageDelayed(Message.obtain(), 5000);

    }

    /**
     * 实现Banner的无限循环播放
     */
    private class MyHandler extends Handler {
        @Override
        public void handleMessage(Message msg) {

            if (bannerInfos != null && bannerInfos.size() > 0) {
                // 实现无限循环，再次发生消息
                myHandler.sendMessageDelayed(Message.obtain(), 5000);

                // 把轮播图切换到下一张
                int item = (mVpBanner.getCurrentItem() + 1) % bannerInfos.size();
                if (item == 0) {// 从最后一张到第一张时，不要动画效果
                    mVpBanner.setCurrentItem(item, false);
                } else {
                    mVpBanner.setCurrentItem(item);
                }
            }
            super.handleMessage(msg);
        }
    }


    @Override
    public String getUrl() {
        return null;
    }

    @Override
    public void onResume() {
        super.onResume();

        if (isFirstIn) {
            loadData(articleid, 1, LOAD_NORMAL);
        }
    }

    private String getCacheKey() {
        return Constant.BASE_URL + Constant.ARTICLE_LIST_URL;
    }

    /**
     * 加载数据
     * @param articleid
     */
    private void loadData(int articleid , int page , final String loadType) {

        if (bannerInfos.size() > 0) {
            bannerInfos.clear();
        }

        Map<String, Object> maps = new HashMap<>();
        maps.put("articleid", articleid);
        maps.put("pageindex",page);
        MyHttp.request(activity, Constant.BASE_URL + Constant.ARTICLE_LIST_URL, maps, MyHttp.POST, true, getCacheKey() + "_" + articleid, new ParseJsonCallback() {
            @Override
            public void onVerifyIsNull() {

            }

            @Override
            public void onVerifyError() {

            }

            @Override
            public void onVerifySuccess(String dataRaw) {
                isFirstIn = false;
                try {
                    parseData(dataRaw,loadType);
                } catch (Exception e) {
                    MyLog.e(TAG, "解析json错误");
                    e.printStackTrace();
                }
            }

            @Override
            public void onServerUnKnownError() {

            }

            @Override
            public void onErrorCodeError(String msg) {

            }
        });
    }

    private void parseData(String dataRaw, String loadType) {
        if (Tools.isEmpty(dataRaw)) {
            MyLog.i("获取主页文章数据", "get home article json error");
            return;
        }

        Gson gson = new Gson();
        ArticleListData listData = gson.fromJson(dataRaw, ArticleListData.class);

        if (listData != null) {
            if (loadType.equals(LOAD_NORMAL)){
                if (articleInfos.size() > 0){
                    articleInfos.clear();
                }
            }
            articleInfos.addAll(listData.datalist);
            nowpage = listData.nowpage;
            totalpage = listData.totalpages;

            bannerInfos.addAll(listData.banner);
            mHandler.sendEmptyMessage(REFRESH_HOME_UI);
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        if (myHandler != null) {
            myHandler.removeCallbacksAndMessages(null);
        }
    }

}
